package student;

import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;

import java.text.SimpleDateFormat;
import java.util.Date;

//java程序的入口地址
public class ExcelUtil {
    public static String getStringCellValue(XSSFCell cell) {
        String cellValue = "";
        if(cell == null){
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                cellValue = cell.getStringCellValue();
                //
                break;
            case NUMERIC:
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    // 处理日期格式、时间格式

                    SimpleDateFormat sdf = null;

                    if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
                        sdf = new SimpleDateFormat("HH:mm");
                    } else {// 日期
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                    }
                    Date date = cell.getDateCellValue();
                    cellValue = sdf.format(date);

                } else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式：m月d日(通过判断单元格的格式id解决，id的值是58)

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    double value = cell.getNumericCellValue();

                    Date date = org.apache.poi.ss.usermodel.DateUtil

                            .getJavaDate(value);

                    cellValue = sdf.format(date);
                }
//                cellValue = new DecimalFormat("yyyy-MM-dd").format(new Date((long)cell.getNumericCellValue()));
                break;
            case BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            default:
                cellValue = "";
                break;
        }
        return cellValue;
    }
}
